package com.dhl.cloud.websocket;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dhl.cloud.config.ConfiguratorForClientIp;
import com.dhl.cloud.websocket.entity.Message;
import com.dhl.cloud.websocket.service.MessageService;
import com.dhl.cloud.websocket.service.RoomService;

/**
 * 用户连接进入到课程lession的直播房间
 */
@ServerEndpoint(value = "/websocket", configurator = ConfiguratorForClientIp.class)
@Component
public class Connection {


//    /**
//     * 在线总人数
//     */
//    private static volatile AtomicInteger onlineCount = new AtomicInteger(0);

    private static RoomService roomService;

    private static MessageService messageService;

//
//    private static CommandService commandService;

    @Autowired
    public void setRoomService(RoomService roomService) {
        Connection.roomService = roomService;
    }
//
    @Autowired
    public void setMessageService(MessageService messageService) {
        Connection.messageService = messageService;
    }

//    @Autowired
//    public void setCommandService(CommandService commandService) {
//        Connection.commandService = commandService;
//    }

//    /**
//     * 某个客户端的ip
//     */
//    private String ip;

    /**
     * 某个客户端的username
     */
    private String username;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	/**
     * 某个客户端的lessionid
     */
    private String roomId;

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;


    public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	/**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
//        ip = (String) session.getUserProperties().get("clientIp");
//        //未进任何房间时，将本次连接放到大厅里面
//        roomService.enterLobby(this);
//        System.out.println("用户: {}, 连接到服务器,当前在线人数为：{}"+ ip+ onlineCount.incrementAndGet());
        //
//        roomService.enterRoom(lessionid, this);
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
//        //离开大厅
//        roomService.leaveLobby(this);
        //即使连接错误，回调了onError方法，最终也会回调onClose方法，所有退出房间写在这里比较合适
        roomService.leaveRoom(roomId, this);
        //在线数减1
        System.out.println("1111111111----- "+roomId);
//        System.out.println("用户: {}, 关闭连接，退出房间: {}, 当前在线人数为:{}"+ip+ roomId+ onlineCount.addAndGet(-1));
    }

    /**
     * 连接发生错误时调用的方法
     */
    @OnError
    public void onError(Session session, Throwable error) {
//        System.out.println("用户连接错误: {}"+ip);
        error.printStackTrace();
    }

    /**
     * 收到客户端消息后调用的方法
     * @param stringMessage 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(Session session, String stringMessage) {
        Message message = JSON.parseObject(stringMessage, Message.class);
        System.out.println("收到来自: {}, 信息：{}"+message.getCommand());
//        System.out.println("收到来自: {}, 信息：{}"+ip+JSON.toJSONString(message));
        switch (message.getCommand()) {
            case Message.TYPE_COMMAND_ROOM_ENTER:
                this.username = message.getUsername();
                this.roomId = message.getRoomId();
                enterRoom(message);
                //服务器主动向所有在线的人推送房间列表
                pushRoomList();
                break;
            case Message.TYPE_COMMAND_DIALOGUE:
                messageService.sendMessageForEveryInRoom(message);
                break;
            case Message.TYPE_COMMAND_ROOM_LIST:
                //前端从服务器拉取房间列表
                pullRoomList(message);
                break;
            case Message.TYPE_COMMAND_READY:
            case Message.TYPE_COMMAND_OFFER:
            case Message.TYPE_COMMAND_ANSWER:
            case Message.TYPE_COMMAND_CANDIDATE:
//                messageService.sendMessageForEveryExcludeSelfInRoom(message);
                // 修改为支持定向发送
                if (message.getTarget() != null && !message.getTarget().isEmpty()) {
                    messageService.sendMessageToTarget(message);
                } else {
                    messageService.sendMessageForEveryExcludeSelfInRoom(message);
                }
                break;

            default:
        }
    }

    /**
     * 返回给自己是加入房间还是创建房间
     * @param message
     */
    private void  enterRoom(Message message) {
        message.setMessage(roomService.enterRoom(roomId, this));
        try {
            session.getBasicRemote().sendText(JSON.toJSONString(message));
        } catch (IOException e) {
        	System.out.println("加入房间还是创建房间失败: {}"+ e);
        }
    }

    private void pullRoomList(Message message) {
        message.setMessage(JSON.toJSONString(roomService.queryAllRoomName(), SerializerFeature.WriteNullListAsEmpty));
        try {
            session.getBasicRemote().sendText(JSON.toJSONString(message));
        } catch (IOException e) {
        	System.out.println("获取数据失败：{}"+e);
        }
    }

    private void pushRoomList() {
        //告诉每个终端更新房间列表
        Message roomListMessage = new Message();
        roomListMessage.setCommand(Message.TYPE_COMMAND_ROOM_LIST);
        roomListMessage.setMessage(JSON.toJSONString(roomService.queryAllRoomName(),SerializerFeature.WriteNullListAsEmpty));
        messageService.sendMessageForAllOnline(roomListMessage);
    }
}
